package org.openclinic.service.impl;

import java.util.Date;
import java.util.List;

import org.openclinic.domain.Document;
import org.openclinic.exception.DomainException;
import org.openclinic.exception.ErrorCodes;
import org.openclinic.repository.DocumentRepository;
import org.openclinic.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

@Service
public class DocumentServiceImpl implements DocumentService {
	
	@Autowired
	private DocumentRepository documentRepository;
	
	@Override
	public void delete(long id) {
		documentRepository.delete(id);
	}
	
	@Override
	public Document find(long id) {
		return documentRepository.findOne(id);
	}
	
	@Override
	public List<Document> list() {
		return documentRepository.findAll();
	}
	
	@Override
	public Document save(Document document) {
		try {
			if (document.getCreationDate() == null) {
				document.setCreationDate(new Date());
			}
			return documentRepository.save(document);
		} catch (DataIntegrityViolationException e) {
			throw new DomainException("document", "name", ErrorCodes.UNIQUE_VIOLATED, String.valueOf(document.getDocumentId()));
		}
	}
}
